package reflect;

import reflect.ann.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

/**
 * 调用与Test3被@AutoRunClass标注的类中所有被@AutoRunMethod标注的方法
 */
public class Test3 {
    public static void main(String[] args) throws Exception{
        File dir = new File(
                Test3.class.getResource(".").toURI()
        );
        String packageName = Test3.class.getPackage().getName();
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for (File sub : subs){
            String filename = sub.getName();
            String classname = filename.substring(0,filename.indexOf("."));
            if (classname.contains("$")){
                continue;
            }
            Class cls = Class.forName(packageName+"."+classname);
            if(cls.isAnnotationPresent(AutoRunClass.class)){
                System.out.println("实例化:"+classname);
                Object obj = cls.newInstance();
                Method[] methods = cls.getDeclaredMethods();
                for(Method method : methods){
                    if(method.isAnnotationPresent(AutoRunMethod.class)){
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int value = arm.value();
                        System.out.println("调用了"+cls.getName()+"的"+method.getName()+"方法"+value+"次");
                        for (int i=0;i<value;i++) {
                            method.invoke(obj);
                        }
                    }
                }
            }
        }
    }
}
